package com.example.zhu95.mytimber.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.Pair;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.zhu95.mytimber.R;
import com.example.zhu95.mytimber.activity.PlaylistDetailActivity;
import com.example.zhu95.mytimber.adapters.PlaylistGridAdapter;
import com.example.zhu95.mytimber.adapters.PlaylistLinearAdapter;
import com.example.zhu95.mytimber.entity.PlayListBean;
import com.example.zhu95.mytimber.utils.PlaylistUtils;
import com.example.zhu95.mytimber.utils.Util;
import com.pixplicity.multiviewpager.MultiViewPager;

import java.util.List;

import static android.support.v4.app.ActivityOptionsCompat.makeSceneTransitionAnimation;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.example.zhu95.mytimber.ConstantValue.CURRENT_VIEW_MODE;
import static com.example.zhu95.mytimber.ConstantValue.DEFAULT_VIEW;
import static com.example.zhu95.mytimber.ConstantValue.GRID_VIEW;
import static com.example.zhu95.mytimber.ConstantValue.LINEAR_VIEW;
import static com.example.zhu95.mytimber.ConstantValue.PLAYLIST_NAME;

/**
 * @author zhu95
 */
public class PlaylistFragment extends BaseFragment {

    RecyclerView recyclerViewPlaylist;
    MultiViewPager multiViewPager;
    PlaylistGridAdapter playlistGridAdapter = null;
    GridLayoutManager gridLayoutManager;
    PlaylistLinearAdapter playlistLinearAdapter = null;
    LinearLayoutManager linearLayoutManager;
    int currentViewMode = DEFAULT_VIEW;
    List<PlayListBean> playlists;
    MyFragmentPagerAdapter pagerAdapter;
    Menu menu;
    private boolean showDefault = true;

    // fixme: 2018/3/28 保存视图模式和是否展示自动生成的列表
    public PlaylistFragment() {
        // Required empty public constructor
    }

    View.OnClickListener itemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentActivity activity = PlaylistFragment.this.getActivity();
            Intent intent = new Intent(activity, PlaylistDetailActivity.class);
            intent.putExtra(PLAYLIST_NAME, v.getTag().toString());

            //如果当前显示是默认模式
            if (currentViewMode == DEFAULT_VIEW) {
                //if (multiViewPager.getVisibility() == VISIBLE) {
                View foregroundView = v.findViewById(R.id.foreground_view);
                int color = (int) (foregroundView.getTag(R.string.share_playlist_fore));
                intent.putExtra(getString(R.string.share_playlist_fore), color);
                ActivityOptionsCompat activityOptionsCompat = makeSceneTransitionAnimation(
                        getActivity(),
                        Pair.create(v.findViewById(R.id.tv_playlist_name), getContext().getString(R.string.share_playlist_name)),
                        Pair.create(v.findViewById(R.id.image_multi_pager), getContext().getString(R.string.share_playlist_img)),
                        Pair.create(foregroundView, getContext().getString(R.string.share_playlist_fore)));
                activity.startActivity(intent, activityOptionsCompat.toBundle());
            } else {
                activity.startActivity(intent);
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        super.onCreateView(inflater, container, savedInstanceState);

        View view = inflater.inflate(R.layout.fragment_playlist, container, false);
        // AppCompatActivity rootActivity = (AppCompatActivity) getActivity();

        Toolbar toolbar = view.findViewById(R.id.toolbar);
        rootActivity.setSupportActionBar(toolbar);
        toolbar.setTitle(R.string.playlist);

        DrawerLayout drawer = (DrawerLayout) rootActivity.findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                rootActivity, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        setHasOptionsMenu(true);

        initMainView(view);

        return view;
    }

    private void initMainView(View view) {
        //获取播放列表的数据
        playlists = PlaylistUtils.INSTANCE.getAllPlaylistData();

        recyclerViewPlaylist = view.findViewById(R.id.recycler_view_playlist);
        linearLayoutManager = new LinearLayoutManager(view.getContext());
        gridLayoutManager = new GridLayoutManager(view.getContext(), 2);
        playlistGridAdapter = new PlaylistGridAdapter(playlists, itemClickListener);
        playlistLinearAdapter = new PlaylistLinearAdapter(playlists, itemClickListener);

        //使用 MultiViewPager
        multiViewPager = view.findViewById(R.id.multi_viewpager);
        setPagerAdapter();
        setViewMode(currentViewMode);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_playlist_popup, menu);
        this.menu = menu;
        menu.findItem(R.id.action_viewas).setVisible(true);
        menu.findItem(R.id.action_order_by).setVisible(false);
        menu.findItem(R.id.view_default).setVisible(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.view_default) {
            setViewMode(DEFAULT_VIEW);
        } else if (itemId == R.id.view_grid) {
            setViewMode(GRID_VIEW);
        } else if (itemId == R.id.view_list) {
            setViewMode(LINEAR_VIEW);
        } else {
            switch (itemId) {
                case R.id.new_playlist:
                    new MaterialDialog.Builder(rootActivity)
                            .input(R.string.enter_playlist_name, R.string.empty_str, new MaterialDialog.InputCallback() {
                                @Override
                                public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                    boolean isSuccess = PlaylistUtils.INSTANCE.createPlaylist(input.toString());
                                    if (!isSuccess) {
                                        Toast.makeText(rootActivity, R.string.create_playlist_error, Toast.LENGTH_SHORT).show();
                                    } else {
                                        onDataSetChange();
                                    }
                                }
                            })
                            .positiveText(android.R.string.ok)
                            .negativeText(android.R.string.cancel).show();
                    break;
                case R.id.hide_auto_playlist:
                    showDefault = false;
                    menu.findItem(R.id.hide_auto_playlist).setVisible(false);
                    menu.findItem(R.id.show_auto_playlist).setVisible(true);
                    onDataSetChange();
                    break;
                case R.id.show_auto_playlist:
                    showDefault = true;
                    menu.findItem(R.id.hide_auto_playlist).setVisible(true);
                    menu.findItem(R.id.show_auto_playlist).setVisible(false);
                    onDataSetChange();
                    break;
                default:
            }
        }
        return true;
    }

    private void onDataSetChange() {
        List<PlayListBean> newList;
        if (showDefault) {
            newList = PlaylistUtils.INSTANCE.getAllPlaylistData();
        } else {
            newList = PlaylistUtils.INSTANCE.getUserAddLists();
        }
        if (Util.INSTANCE.listEquals(playlists, newList)) {
            return;
        }
        playlists.clear();
        playlists.addAll(newList);
        playlistGridAdapter.notifyDataSetChanged();
        playlistLinearAdapter.notifyDataSetChanged();
        setPagerAdapter();
    }

    void setViewMode(int viewMode) {
        if (viewMode == DEFAULT_VIEW) {
            recyclerViewPlaylist.setVisibility(GONE);
            multiViewPager.setVisibility(VISIBLE);
            currentViewMode = DEFAULT_VIEW;
        } else {
            setRecyclerViewMode(viewMode);
        }
    }

    public void setRecyclerViewMode(int viewMode) {
        if (viewMode == LINEAR_VIEW) {
            currentViewMode = viewMode;
            recyclerViewPlaylist.setAdapter(playlistLinearAdapter);
            recyclerViewPlaylist.setLayoutManager(linearLayoutManager);
        } else if (viewMode == GRID_VIEW) {
            currentViewMode = viewMode;
            recyclerViewPlaylist.setAdapter(playlistGridAdapter);
            recyclerViewPlaylist.setLayoutManager(gridLayoutManager);
        }
        recyclerViewPlaylist.setVisibility(VISIBLE);
        multiViewPager.setVisibility(GONE);
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle args = getArguments();
        if (args != null) {
            int viewMode = args.getInt(CURRENT_VIEW_MODE);
            if (currentViewMode != viewMode) {
                setViewMode(viewMode);
            }
        }
        onDataSetChange();
    }

    @Override
    public void onPause() {
        super.onPause();
        Bundle args = new Bundle();
        args.putInt(CURRENT_VIEW_MODE, currentViewMode);
        setArguments(args);
    }

    private void setPagerAdapter() {
        pagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager());
        pagerAdapter.setPlaylists(playlists);
        pagerAdapter.setItemClickListener(itemClickListener);
        multiViewPager.setAdapter(pagerAdapter);
    }

    // MARK:2018/3/15 FragmentStatePagerAdapter 改为FragmentPagerAdapter   见 http://blog.csdn.net/rankun1/article/details/51842471
    public static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private List<PlayListBean> playlists;
        private View.OnClickListener itemClickListener;

        @Override
        public Fragment getItem(int position) {
            return MutilViewPageFragment.create(position, playlists, itemClickListener);
        }

        @Override
        public int getCount() {
            return playlists.size();
        }

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public List<PlayListBean> getPlaylists() {
            return playlists;
        }

        public void setPlaylists(List<PlayListBean> playlists) {
            this.playlists = playlists;
        }

        public View.OnClickListener getItemClickListener() {
            return itemClickListener;
        }

        public void setItemClickListener(View.OnClickListener itemClickListener) {
            this.itemClickListener = itemClickListener;
        }

    }

}
